<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="AddEdit">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
        v-show="arr.length > 0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="editFn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: '',
      age: '',
      gender: '女',
      editIndex: null,
      arr: [
        { name: 'Tom2', age: 25, sex: '女' },
        { name: '小李', age: 18, sex: '男' },
      ],
    }
  },
  methods: {
    delFn(index) {
      this.arr.splice(index, 1)
    },
    editFn(id) {
      this.name = this.arr[id].name
      this.age = this.arr[id].age
      this.gender = this.arr[id].sex
      this.editIndex = id
    },
    AddEdit() {
      let newObj = {
        name: this.name,
        age: this.age,
        sex: this.gender,
      }
      if (this.editIndex !== null) {
        //如果有索引值编辑更新
       // console.log(this.name, this.age, this.gender)
        this.$set(this.arr, this.editIndex, newObj)
        console.log('编辑')
      } else {
        //console.log('添加')
        if(this.name.trim()===''||this.age===0) return alert('添加数据 请完善表单！')
        this.arr.push(newObj)
      }
    },
  },
}
</script>
